/***
 * Copyright (c) 2021-2031 murenchao
 * fig is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *       http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package cool.taomu.software.fig.mqtt.broker.impl

import com.google.common.collect.ArrayListMultimap
import cool.taomu.software.fig.mqtt.broker.MQTTCache
import cool.taomu.software.fig.mqtt.broker.entity.MessageEntity
import cool.taomu.software.fig.mqtt.broker.inter.IPublishObserver
import cool.taomu.software.fig.mqtt.broker.inter.IPublishObserver.Type
import cool.taomu.software.fig.mqtt.utils.CommonUtils
import java.util.Vector
import org.apache.commons.lang3.SerializationUtils
import org.slf4j.LoggerFactory

final class PublishObservable {
	var LOG = LoggerFactory.getLogger(PublishObservable);
	val static ArrayListMultimap<String, IPublishObserver> observers = ArrayListMultimap.create();
	val static instance = new PublishObservable();
	MQTTCache cache = MQTTCache.instance;

	private new() {
		
	}

	def synchronized static getInstance() {
		return instance;
	}

	def synchronized void register(String key, IPublishObserver arg) {
		LOG.info("register :" + key);
		observers.put(key, arg);
	}

	def synchronized void unregister(String key) {
	    LOG.info("unregister :" + key);
		observers.removeAll(key);
	    LOG.info("unregister :" + observers.size);
	}

	def void start(String clientId, Type type) {
		synchronized (observers) {
			LOG.info("observers number : {}" , observers.size);
			val messages = new Vector<MessageEntity>();
			if (type.equals(Type.RETAIN)) {
				// 获取所有存储的ratein消息
				var rateins = cache.loadRetain();
				LOG.info("rateins 消息数 : {}" , rateins.size)
				messages.addAll(rateins);
			}
			if (type.equals(Type.MESSAGE)) {
				messages.addAll(#[cache.loadMessage(clientId)]);
			}
			observers.forEach([ k, v |
				CommonUtils.exec([
					v.update(SerializationUtils.clone(messages), type)
				])
			])
		}
	}
}
